
// * - Wire ServerApp for PCMod - * \\
// * Purpose: Provide a selection of wire inputs and outputs * \\
// * Client: WireClient Program * \\
// * Ports: INT25(SV), EXT24(CL) * \\

APP.Name = "Wire Host" -- Nice Name
APP.AppName = "wire" -- Internal Name

// --- Mandatory Functions --- \\

function APP:Useable()
	// Can the ServerApp be used on this server?
	// Msg( "PCMod-> WireMod: " .. tostring( WireMod ) )
	return (WireAddon == 1);
end

function APP:Initialize()
	// Server first spawned
	
	self.Server.WireDebugName = self.Server.PrintName -- Setup wire variables
	self.Server.Inputs = Wire_CreateInputs( self.Server.Entity, { "1", "2", "3", "4", "5" } ) -- Create the wire inputs
	self.Server.Outputs = Wire_CreateOutputs( self.Server.Entity, {"1", "2", "3", "4", "5" } ) -- Create the wire outputs
	
	self.Server.Data[self.Server:EntIndex()].WireInputs = {} -- Refresh Wire Inputs
	
	function self.Server:TriggerInput(iname, value) -- Add wire functions
		self.Data[self:EntIndex()].WireInputs[ iname ] = value -- (Note that the scope now changes to the server entity, not the app)
	end
	
end
APP.Init = APP.Initialize -- For ease of use

function APP:StartUp()
	// Server turned ON
	if (!self.Server) then return end -- No server = no app
	
	self.Server:OpenPort( 25, "sapp" ) -- Open wire port, redirect traffic to us
	
end

function APP:ShutDown()
	// Server turned OFF
	if (!self.Server) then return end -- No Server = no app
	
	self.Server:ClosePort( 25 ) -- Close up wire port
	
end

function APP:PacketRecieved( packet )
	// Packet has arrived for us, on a port opened by us
	local pck = self:DecodePacket( packet )
	if (pck.Port == 25) then
		if (pck.Body[1] == "wire_setoutput") then self:SetOutput( pck.Body[2], pck.Body[3] ) end
		if (pck.Body[1] == "wire_getinputs") then self:SendInputs( pck.SourceIP ) end
	end
end

function APP:KillHost()
	self:ShutDown() -- Make sure we shut down properly
end


// --- Non Required Functions --- \\ (But still needed by this app)

function APP:DecodePacket( packet )
	local tmp = {}
		tmp.SourceIP = packet[1]
		tmp.DestIP = packet[2]
		tmp.Port = tonumber( packet[3] )
		tmp.Body = packet[4]
	return tmp
end

function APP:SetOutput( id, val )
	if (!id) then return end
	if (!val) then return end
	Wire_TriggerOutput( self.Server.Entity, tostring( id ), tonumber( val ) )
end

function APP:SendInputs( ip )
	local data = {}
	data = self.Server.Data[self.Server:EntIndex()].WireInputs
	local packet = { self.Server.Data[self.Server:EntIndex()].IP, ip, 24, { "wireinputs", data } }
	local result = self.Server:SendPacket( packet )
end